package approve.action;


import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
import java.util.Timer;
import java.util.TimerTask;

import org.xmlpull.v1.XmlPullParser;

import memo.action.Memo_listview;
import model.pojo.Employee;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.graphics.Color;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.AttributeSet;
import android.util.Log;
import android.util.Xml;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.LayoutInflater.Factory;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import approve.adapter.EApproveAdapter;
import approve.dao.ApproveDocDao;
import approve.dao.ReceiverDocumentDAO;

public class MainEApproval extends Activity{
	
	TextView logout,username,home,welcome;
	ListView lstApprove;
	Button buttonBack;
	public static Timer timer;
	public static NotificationManager mNotificationManager=null;
	public static int SIMPLE_NOTFICATION_ID;
	EApproveAdapter eApproveAdapter;
	public String Text="";
	int[] countarray=new int[14];
//	private final Handler uiHandler=new Handler();
//	private boolean isUpdateRequired=false;
	public static String URL_LIST_PRODUCT = "http://14.63.212.204/eli-android-center/data/auto-update/listitem.xml";
	ProgressDialog mProgressDialog;
	public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
	String link = "";
	String newversion="";
	String oldversion="";
	ReceiverDocumentDAO rd = new ReceiverDocumentDAO();
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		try{
			initall();
			getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);

		}catch(Exception e){
			e.printStackTrace();
			Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
			i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
			startActivity(i);
		}
	}
	
	
	private void initall(){
		setContentView(R.layout.maineapproval);
		getInit();
		Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
		Date currentLocalTime = cal.getTime();
		System.out.println("zone: "+TimeZone.getDefault().getDisplayName()+" -- "+TimeZone.getDefault().getID()+" --- "+currentLocalTime.getHours());
		if(currentLocalTime.getHours()>=8 && currentLocalTime.getHours()<=22){
			showNotificationMessage();
		}
		loadContentList();
		checkUpdate();
		buttonBack.setOnClickListener(btBackClick);
	}
	
	private OnClickListener btBackClick = new OnClickListener() {
		
		@Override
		public void onClick(View v) {
			buttonBack.setTextColor(Color.parseColor("#1188ff"));
			LoginActivity.flagruntimer=true;
			LoginActivity.soluong=0;
			LoginActivity.emp= new Employee();
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			timer.cancel();
			Intent i=new Intent(MainEApproval.this, LogoutActivity.class);
			startActivity(i);
			finish();
		}
	};
	
	private void getInit(){
		logout=(TextView)findViewById(R.id.logout);
		username=(TextView)findViewById(R.id.username);
		logout.setText(LoginActivity.lang.getString("Logout"));
		logout.setOnClickListener(listenerLogout);
		username.setText(LoginActivity.emp.getUserName());
		welcome = (TextView)findViewById(R.id.welcome);
		welcome.setText(LoginActivity.lang.getString("ac_Welcome"));
		buttonBack = (Button)findViewById(R.id.buttonBack);
		lstApprove = (ListView)findViewById(R.id.listApproval);
		mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
	}
	
	public void loadContentList(){
		countarray=ApproveDocDao.countall(LoginActivity.emp.getIdemployee(), LoginActivity.database);
		eApproveAdapter = new EApproveAdapter(getApplicationContext(),listAllApprove(LoginActivity.typeLang),LoginActivity.lang,LoginActivity.emp,LoginActivity.database,LoginActivity.typeLang,countarray);
		lstApprove.setAdapter(eApproveAdapter);
		OnItemClickListener listener = new OnItemClickListener() {
			public void onItemClick(AdapterView<?> arg0, View arg1,
					int arg2, long arg3) {
				String item = arg0.getItemAtPosition(arg2).toString();
				if(item.equals(LoginActivity.lang.getString("pending-document"))){
					Intent intent = new Intent(MainEApproval.this,App_PendingDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("not-approved-document"))){
					Intent intent = new Intent(MainEApproval.this,App_NotApproveDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("document_approval"))){
					Intent intent = new Intent(MainEApproval.this,App_ApprovedDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("docDecline"))){
					Intent intent = new Intent(MainEApproval.this,App_DeclineDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("metting_pending"))){
					Intent intent = new Intent(MainEApproval.this,App_MeetingDocPending.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empApprove"))){
					Intent intent = new Intent(MainEApproval.this,App_ReferenceDoc_Approved.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empNotApprove"))){
					Intent intent = new Intent(MainEApproval.this,App_ReferenceDoc_Waiting.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("mydocsending"))){
					Intent intent = new Intent(MainEApproval.this,My_App_SendingDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("mydocsave"))){
					Intent intent = new Intent(MainEApproval.this,My_App_SaveDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("mydocappro"))){
					Intent intent = new Intent(MainEApproval.this,My_App_ApproveDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("mydeclinedoc"))){
					Intent intent = new Intent(MainEApproval.this,My_App_DeclineDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("mymeetingdcsending"))){
					Intent intent = new Intent(MainEApproval.this,My_App_MeetingSendingDocument.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.getString("recycle_receveidoc"))){
					Intent intent = new Intent(MainEApproval.this,My_Approve_RecycleBin.class);
					startActivityForResult(intent, 0);
				}
				else if(item.equals(LoginActivity.lang.getString("recylce_sending_document"))){
					Intent intent = new Intent(MainEApproval.this,My_Sending_RecycleBin.class);
					startActivityForResult(intent, 0);
				}
				else if(item.equals(LoginActivity.lang.getString("all_label"))){
					Intent intent = new Intent(MainEApproval.this,Library_All_Label.class);
					startActivityForResult(intent, 0);
				}else if(item.equals(LoginActivity.lang.get("listprivatememo"))){
					Intent intent = new Intent(MainEApproval.this,Memo_listview.class);
					startActivityForResult(intent, 0);
				}
				finish();
			}
			
		};
		lstApprove.setOnItemClickListener(listener);
	}

	private OnClickListener listenerLogout=new OnClickListener() {

		public void onClick(View v) {
			logout.setTextColor(Color.parseColor("#1188ff"));
			LoginActivity.soluong=0;
			LoginActivity.emp= new Employee();
			LoginActivity.flagruntimer=true;
			mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
			timer.cancel();
			Intent i=new Intent(MainEApproval.this, LogoutActivity.class);
			startActivity(i);
			finish();
		}
	};

	public String[] listAllApprove(String value) {
		String[] menu = new String[21];
		if(LoginActivity.lang.getString("privateMemo")!= null){
			menu[0] = LoginActivity.lang.getString("privateMemo");
		}else{
			menu[0] = "";
		}if(LoginActivity.lang.getString("listprivatememo")!= null){
			menu[1] = LoginActivity.lang.getString("listprivatememo");
		}else{
			menu[1] = "";
		}
		
		if(LoginActivity.lang.getString("received-document")!= null){
			menu[2] = LoginActivity.lang.getString("received-document");
		}else{
			menu[2] = "";
		}
		if(LoginActivity.lang.getString("pending-document")!= null){
			menu[3] = LoginActivity.lang.getString("pending-document");
		}else{
			menu[3] = "";
		}
		if(LoginActivity.lang.getString("not-approved-document")!= null){
			menu[4] = LoginActivity.lang.getString("not-approved-document");
		}else{
			menu[4] = "";
		}
		if(LoginActivity.lang.getString("document_approval")!= null){
			menu[5] = LoginActivity.lang.getString("document_approval");
		}else{
			menu[5] = "";
		}
		if(LoginActivity.lang.getString("docDecline")!= null){
			menu[6] = LoginActivity.lang.getString("docDecline");
		}else{
			menu[6] = "";
		}
		if((LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empApprove"))!=null){
			menu[7] = LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empApprove");
		}else{
			menu[7] ="";
		}
		if((LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empNotApprove"))!= null){
			menu[8] = LoginActivity.lang.getString("reference_document")+"-"+LoginActivity.lang.getString("empNotApprove");
		}else{
			menu[8] = "";
		}
		if(LoginActivity.lang.getString("metting_pending")!= null){
			menu[9] = LoginActivity.lang.getString("metting_pending");
		}else{
			menu[9] = "";
		}
		if(LoginActivity.lang.getString("my-document")!= null){
			menu[10] = LoginActivity.lang.getString("my-document");
		}else{
			menu[10] = "";
		}
		if(LoginActivity.lang.getString("mydocsending")!= null){
			menu[11] = LoginActivity.lang.getString("mydocsending");
		}else{
			menu[11] = "";
		}
		if(LoginActivity.lang.getString("mydocsave")!= null){
			menu[12] = LoginActivity.lang.getString("mydocsave");
		}else{
			menu[12] = "";
		}
		if(LoginActivity.lang.getString("mydocappro")!= null){
			menu[13] = LoginActivity.lang.getString("mydocappro");
		}else{
			menu[13] = "";
		}
		if(LoginActivity.lang.getString("mydeclinedoc")!= null){
			menu[14] = LoginActivity.lang.getString("mydeclinedoc");
		}else{
			menu[14] = "";
		}
		if(LoginActivity.lang.getString("mymeetingdcsending")!= null){
			menu[15] = LoginActivity.lang.getString("mymeetingdcsending");
		}else{
			menu[15] = "";
		}
		if(LoginActivity.lang.getString("recycle_bin")!= null){
			menu[16] = LoginActivity.lang.getString("recycle_bin");
		}else{
			menu[16] = "";
		}
		if(LoginActivity.lang.getString("recycle_receveidoc")!= null){
			menu[17] = LoginActivity.lang.getString("recycle_receveidoc");
		}else{
			menu[17] = "";
		}
		if(LoginActivity.lang.getString("recylce_sending_document")!= null){
			menu[18] = LoginActivity.lang.getString("recylce_sending_document");
		}else{
			menu[18] = "";
		}
		if(LoginActivity.lang.getString("library_document")!= null){
			menu[19] = LoginActivity.lang.getString("library_document");
		}else{
			menu[19] = "";
		}
		if(LoginActivity.lang.getString("all_label")!= null){
			menu[20] = LoginActivity.lang.getString("all_label");
		}else{
			menu[20] = "";
		}
		return menu;
	}
	
	@Override
	public void onBackPressed() {
		LoginActivity.flagruntimer=true;
		LoginActivity.soluong=0;
		LoginActivity.emp= new Employee();
		mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
		timer.cancel();
		Intent i=new Intent(MainEApproval.this, LogoutActivity.class);
		startActivity(i);
		finish();
	}
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		super.onCreateOptionsMenu(menu);
		MenuInflater inflater = new MenuInflater(getApplicationContext());
		if(LoginActivity.typeLang.equals("EN")){
			inflater.inflate(R.menu.option_main_menu, menu);
		}else if(LoginActivity.typeLang.equals("VN")){
			inflater.inflate(R.menu.option_main_menuvn, menu);
		}else{
			inflater.inflate(R.menu.option_main_menukr, menu);
		}

		setMenuBackground();
		return true;
	}
	protected void setMenuBackground(){
		Log.d("", "Enterting setMenuBackGround");  
		getLayoutInflater().setFactory( new Factory() {  
			@Override
			public View onCreateView(String name, Context context,
					AttributeSet attrs) {
				if ( name.equalsIgnoreCase( "com.android.internal.view.menu.IconMenuItemView" ) ) {  
					try { 
						LayoutInflater f = getLayoutInflater();  
						final View view = f.createView( name, null, attrs );  
						new Handler().post( new Runnable() {  
							public void run () {  
								view.setBackgroundResource( R.drawable.border_footer);  
							}  
						} );  
						return view;  
					}  
					catch ( InflateException e ) {}  
					catch ( ClassNotFoundException e ) {}  
				}  
				return null;  
			}  
		});  
	}
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if(LoginActivity.typeLang.equals("VN")){
			switch (item.getItemId()) {
			case R.id.menu_eappvn:
				processMenuEApproval();
				return true;
			case R.id.menu_primemovn:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else if(LoginActivity.typeLang.equals("KR")){
			switch (item.getItemId()) {
			case R.id.menu_eappkr:
				processMenuEApproval();
				return true;
			case R.id.menu_primemokr:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}else{
			switch (item.getItemId()) {
			case R.id.menu_eapp:
				processMenuEApproval();
				return true;
			case R.id.menu_primemo:
				processMenuPrivateMemo();
				return true;
			default:
				return super.onOptionsItemSelected(item);
			}
		}
	}
	
	public void processMenuEApproval(){
		loadContentList();
	}
	
	public void processMenuPrivateMemo(){
		Intent intent = new Intent(MainEApproval.this,Memo_listview.class);
		startActivity(intent);
		finish();
	}
	private void showNotificationMessage(){
		try{
			if(LoginActivity.flagruntimer==true){
				LoginActivity.flagruntimer=false;
				timer=new Timer();
				timer.scheduleAtFixedRate(new mainTask(), 500, 10000);
			}
		}catch(Exception e){
			writelog(e.getMessage());
		}
		
	}
	
	private class mainTask extends TimerTask {
		@Override
		public void run() {
			try{
				Calendar cal = Calendar.getInstance(TimeZone.getTimeZone(TimeZone.getDefault().getID()));
				Date currentLocalTime = cal.getTime();
				System.out.println("zone: "+TimeZone.getDefault().getDisplayName()+" -- "+TimeZone.getDefault().getID()+" --- "+currentLocalTime.getHours());
				if(currentLocalTime.getHours()>=8 && currentLocalTime.getHours()<=22){
					if(LoginActivity.flagruntimer==false){
						final Notification notifyDetails;
						int count=rd.countAllNewMessage(LoginActivity.emp.getIdemployee(), LoginActivity.database);
						if(count>0){
							if(LoginActivity.soluong<count){
								LoginActivity.soluong=count;
								notifyDetails = new Notification(R.drawable.mail,count + " new message", System.currentTimeMillis());
								notifyDetails.defaults = Notification.DEFAULT_ALL;
								Context context = getApplicationContext();
								CharSequence contentTitle = "You have " + LoginActivity.soluong + " new message";
								CharSequence contentText = "click me to view detail";
								Intent notifyIntent = new Intent(MainEApproval.this,App_NotApproveDocument.class);
								PendingIntent intent = PendingIntent.getActivity(MainEApproval.this,0, notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
								notifyDetails.setLatestEventInfo(context, contentTitle,contentText, intent);
								mNotificationManager.notify(SIMPLE_NOTFICATION_ID,notifyDetails);
							}else{
								LoginActivity.soluong=count;
							}
						}else{
							if(LoginActivity.soluong!=0){
								LoginActivity.soluong=0;
								mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
							}
						}
					}else{
						LoginActivity.soluong=0;
						mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
						timer.cancel();
					}
				}else{
					LoginActivity.soluong=0;
					mNotificationManager.cancel(MainEApproval.SIMPLE_NOTFICATION_ID);
//					timer.cancel();
				}
				
				
			}catch(Exception e){
				MainEApproval.this.writelog(e.getMessage());
			}
			
		}
	}
	
	private void checkUpdate(){
		if(getCheckProduct()==false){
			AlertDialog.Builder builder = new AlertDialog.Builder(this);
			builder.setTitle("Update new version");
			builder.setMessage("A new version "+newversion+" of Eli-ERP is available for update\n"
					+ "Would you like to update ?");
			builder.setPositiveButton(LoginActivity.lang.getString("ok"),
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,int which) {
							mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
							timer.cancel();
							downloading();
						}
					});
			builder.setNegativeButton(LoginActivity.lang.getString("cancel"),
					new AlertDialog.OnClickListener() {
						@Override
						public void onClick(DialogInterface dialog,
								int which) {
						}
					});
			builder.show();
		}
	}
	


	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case DIALOG_DOWNLOAD_PROGRESS:
			mProgressDialog = new ProgressDialog(this);
			mProgressDialog.setMessage("Downloading ...");
			mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
			mProgressDialog.setCancelable(false);
			mProgressDialog.show();
			return mProgressDialog;
		default:
			return null;
		}
	}


	public void downloading() {
		new AsyncTask<String, String, String>() {

			@Override
			protected void onPreExecute() {
				super.onPreExecute();
				showDialog(DIALOG_DOWNLOAD_PROGRESS);
			}

			protected void onProgressUpdate(String... progress) {
				mProgressDialog.setProgress(Integer.parseInt(progress[0]));
			}

			@Override
			protected void onPostExecute(String unused) {
				dismissDialog(DIALOG_DOWNLOAD_PROGRESS);
				finish();
			}

			@Override
			protected String doInBackground(String... arg0) {
				try {
					URL url = new URL(link);
					HttpURLConnection c = (HttpURLConnection) url
							.openConnection();
					c.setRequestMethod("GET");
					c.setDoOutput(true);
					c.connect();

					File file = new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/");
					if (!file.exists()) {
						file.mkdir();
					}

					file = new File(Environment.getExternalStorageDirectory()
							+ "/elicenter/" + "EliERP.apk");
					if (!file.exists()) {
						file.createNewFile();
					}

					File outputFile = new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/" + "EliERP.apk");
					FileOutputStream fos = new FileOutputStream(outputFile);

					InputStream is = c.getInputStream();

					byte[] buffer = new byte[1024];

					long total = 0;
					int count;
					int lenghtOfFile = c.getContentLength();
					while ((count = is.read(buffer)) != -1) {
						total += count;
						publishProgress(""
								+ (int) ((total * 100) / lenghtOfFile));
						fos.write(buffer, 0, count);
					}

					fos.flush();
					fos.close();
					is.close();

					Intent intentInstall = new Intent(Intent.ACTION_VIEW);
					intentInstall.setDataAndType(Uri.fromFile(new File(
							Environment.getExternalStorageDirectory()
									+ "/elicenter/" + "EliERP.apk")),
							"application/vnd.android.package-archive");
					startActivity(intentInstall);
				} catch (Exception e) {
					e.printStackTrace();
					writelog(e.getMessage()+"\n"+e.getCause());
				}
				return null;
			}
		}.execute("");
	}
	
	
	public boolean getCheckProduct() {
		try {
			PackageInfo manager = getPackageManager().getPackageInfo(getPackageName(), 0);
			XmlPullParser xmlPullParser = Xml.newPullParser();

			URL url = new URL(URL_LIST_PRODUCT);
			xmlPullParser.setInput(url.openStream(), "UTF-8");

			int eventType;
			@SuppressWarnings("unused")
			String name, size, icon, version, link1, description, pkg;
			int versionCode = 0;
			name = size = icon = version = link1 = description = pkg = "";
			while ((eventType = xmlPullParser.next()) != XmlPullParser.END_DOCUMENT) {
				if (eventType == XmlPullParser.START_TAG) {
					if (xmlPullParser.getName().equals("name")) {
						name = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("package")) {
						pkg = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("size")) {
						size = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version")) {
						version = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("version-code")) {
						versionCode = Integer.parseInt(xmlPullParser.nextText());
					} else if (xmlPullParser.getName().equals("link")) {
						link1 = xmlPullParser.nextText();
					} else if (xmlPullParser.getName().equals("description")) {
						description = xmlPullParser.nextText();
						if(pkg.equals(manager.packageName)){
							if(versionCode>manager.versionCode){
								oldversion=manager.versionName;
								newversion=version;
								link=link1;
								return false;
							}
						}
					}
				}
			}
		} catch (Exception e) {
			e.printStackTrace(System.out);
		}
		return true;
	}
	
	public void writelog(String s){
		try{
			FileOutputStream file = openFileOutput(Environment.getExternalStorageDirectory().toString()+"/lienmo_writelog/log.txt", Context.MODE_APPEND);
			file.write(s.getBytes());
			file.write("-".getBytes());
			file.close();
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	
}